import 'dart:async';

import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/network/http_config.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/main/navigator.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../widget/verification_box/verification_box.dart';
import 'account/profile_complete.dart';

class LoginVerifyCode extends StatelessWidget {
  final String mob;
  final String sig;

  const LoginVerifyCode(this.mob, this.sig, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      bgColor: Colors.white,
      childWidget: _LoginVerifyCode(mob, sig),
    );
  }
}

class _LoginVerifyCode extends StatefulWidget {
  final String mob;
  final String sig;

  const _LoginVerifyCode(this.mob, this.sig, {Key? key}) : super(key: key);

  @override
  State<_LoginVerifyCode> createState() => _LoginVerifyCodeState();
}

class _LoginVerifyCodeState extends State<_LoginVerifyCode> {
  late Timer _timer;
  int curTime = 0;

  startCountdownTimer() {
    curTime = 60;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      curTime--;
      if (curTime <= 0) {
        _timer.cancel();
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    // _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: const EdgeInsets.only(left: 20.0, top: 72.0),
          child: const Text(
            "输入验证码",
            style: TextStyle(
              color: Color(0xFF222222),
              fontSize: 30,
            ),
          ),
        ),
        Container(
          margin: const EdgeInsets.only(left: 20.0, top: 8.0),
          child: Text(
            "验证码已发送至 +86 ${widget.mob}",
            style: const TextStyle(
              color: Color(0xFF222222),
              fontSize: 12,
            ),
          ),
        ),
        Container(
          height: 48,
          margin: const EdgeInsets.only(top: 24),
          child: Center(
            child: VerificationBox(
              type: VerificationBoxItemType.underline,
              count: 4,
              borderColor: ThemeColor.textColor,
              borderWidth: 1,
              textStyle: TextStyle(
                color: ThemeColor.textColor,
                fontWeight: FontWeight.bold,
              ),
              showCursor: true,
              cursorColor: ThemeColor.textColor,
              cursorWidth: 2.5,
              onSubmitted: (value) {
                _login(value);
              },
            ),
          ),
        ),
        Container(
            margin: const EdgeInsets.only(top: 36.0, left: 20.0),
            child: GestureDetector(
              child: Text(
                curTime > 0 ? "$curTime秒后重新获取验证码" : "重新获取验证码",
                style: TextStyle(fontSize: 14, color: ThemeColor.textColor),
              ),
              onTap: () {
                if (curTime <= 0) {
                  startCountdownTimer();
                }
              },
            ))
      ],
    );
  }

  _login(String code) async {
    // final res = await Api.getInstance().login(code);
    // if (res['code'] == 0) {
    //   final prefs = await SharedPreferences.getInstance();
    //   HttpConfig.token = res['data']['token'];
    //   prefs.setString("token", HttpConfig.token);
    //   prefs.setString("memberId", res['data']['memberId']);
    //   Navigator.of(context).pushAndRemoveUntil(
    //       MaterialPageRoute(builder: (ctx) => const ProfileCompleteUi()),
    //       (route) => false
    //   );
    // } else {
    //   ThemeSnackBar.show(context, res['msg']);
    // }

    showLoading();
    final res =
        await Api.getInstance().loginBySms(widget.mob, code, widget.sig);
    if (res['code'] == 0) {
      Provider.memberId = res['data']['memberId'];
      HttpConfig.token = res['data']['token'];
      Provider.loginSign = res['data']['sig'];
      await Provider.cache("memberId", Provider.memberId);
      await Provider.cache("token", HttpConfig.token);
      final userRes = await Api.getInstance().getMemberInfo(Provider.memberId);
      final user = userRes['data'];
      String? inviteCode = await Provider.getCache("invite_code");
      if (inviteCode?.isNotEmpty == true) {
        await Api.getInstance().invite(Provider.memberId, inviteCode!);
      }
      dismissLoading();
      if (user != null &&
          user['nickName']?.toString().isNotEmpty == true &&
          user['profilePhoto']?.toString().isNotEmpty == true &&
          user['bornDate']?.toString().isNotEmpty == true) {
        Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(builder: (ctx) =>  AppMain()),
            (route) => false);
      } else {
        Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(builder: (ctx) => const ProfileCompleteUi()),
            (route) => false);
      }
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }
}
